package com.yesin.geteway.filter;


import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.yesin.geteway.config.AuthConfig;
import com.yesin.geteway.config.FilterConfig;
import com.yesin.geteway.utils.CookieUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.yesin.auth.utils.JwtUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Component
@EnableConfigurationProperties({AuthConfig.class, FilterConfig.class})
public class LoginFilter extends ZuulFilter {

    @Autowired
    private AuthConfig authConfig;

    @Autowired
    private FilterConfig filterConfig;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        // 获取上下文
        RequestContext context = RequestContext.getCurrentContext();
        // 获取请求信息
        HttpServletRequest request = context.getRequest();
        // 拿到url地址
        String requestURL = request.getRequestURL().toString();
        List<String> allowPaths = filterConfig.getAllowPaths();
        for (String allowPath : allowPaths) {
            // 判断url是否包含白名单路径
            if (StringUtils.contains(requestURL, allowPath)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 获取上下文
        RequestContext context = RequestContext.getCurrentContext();
        // 获取请求信息
        HttpServletRequest request = context.getRequest();
        // 解析cokie值，得到token
        String token = CookieUtils.getCookieValue(request, authConfig.getCookieName());

        try {
            // 校验通过，什么都不做，即放行
            JwtUtils.getInfoFromToken(token, authConfig.getPublicKey());
        } catch (Exception e) {
            // 校验出异常
            e.printStackTrace();
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }
        return null;
    }
}
